package com.caimiao.miao.library.database.table;

import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

import com.caimiao.miao.bean.Device;
import com.caimiao.miao.library.database.DBHelperImpl;

public class DeviceDBHelper extends DBHelperImpl<Device> {

    @Override
    protected String getTableName() {
        return DeviceTable.TABLE_NAME;
    }

    public DeviceDBHelper() {
        super();
    }

    public void backup(Device device) {
        if (device == null) return;
        if (!hasDevice(device.getDeviceId())) {
            long ret = insert(device);
            Log.e("DeviceDBHelper", "ret = " + ret);
        } else {
            int ret = update(get(device), DeviceTable.ATTR_DEVICE + " = ?", new String[]{device.getDeviceId()});
            Log.e("DeviceDBHelper", "ret = " + ret);
        }
    }

    public boolean hasDevice(String deviceId) {
        boolean ret = false;
        Cursor cursor = db.query(getTableName(), null,
                DeviceTable.ATTR_DEVICE + " = ?", new String[]{deviceId}, null, null, null);
        if (cursor != null) {
            ret = cursor.moveToFirst();
            cursor.close();
        }
        return ret;
    }

    public String getDeviceId() {
        String ret = null;
        Cursor cursor = db.query(getTableName(), null, null, null, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst())
                ret = cursor.getString(cursor.getColumnIndex(DeviceTable.ATTR_DEVICE));
            cursor.close();
        }
        return ret;
    }

    @Override
    public Device get(Cursor cursor) {
        Device data = new Device();
        data.setDeviceId(cursor.getString(cursor.getColumnIndex(DeviceTable.ATTR_DEVICE)));
        data.setBatteryStatus(cursor.getString(cursor.getColumnIndex(DeviceTable.ATTR_BATTERY)));
        data.setNetStatus(cursor.getString(cursor.getColumnIndex(DeviceTable.ATTR_NET)));
        data.setLatitude(cursor.getDouble(cursor.getColumnIndex(DeviceTable.ATTR_LAT)));
        data.setLongitude(cursor.getDouble(cursor.getColumnIndex(DeviceTable.ATTR_LNG)));
        data.setLocType(cursor.getString(cursor.getColumnIndex(DeviceTable.ATTR_LOC_TYPE)));
        return data;
    }

    @Override
    public ContentValues get(Device data) {
        ContentValues values = new ContentValues();
        values.put(DeviceTable.ATTR_DEVICE, data.getDeviceId());
        values.put(DeviceTable.ATTR_BATTERY, data.getBatteryStatus());
        values.put(DeviceTable.ATTR_NET, data.getNetStatus());
        values.put(DeviceTable.ATTR_LAT, data.getLatitude());
        values.put(DeviceTable.ATTR_LNG, data.getLongitude());
        values.put(DeviceTable.ATTR_LOC_TYPE, data.getLocType());
        return values;
    }

}
